﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DocManagerORM.ORM;
using System.Data;
using System.ComponentModel;
using System.Data.Metadata.Edm;
using System.Reflection;
using System.Collections;
using DocManagerORM.Utils;
using DocManagerControls.Converters;
using DocManagerORM.Caching;
using DS2171Utils;

namespace DocManagerControls.Controls
{
    /// <summary>
    /// Interaction logic for CodificheControl.xaml
    /// </summary>
    public partial class CodificheControl : BaseCusControl
    {
        QueryCodifiche m_QueryCodifiche = new QueryCodifiche();
        CLASSI.GridColumnsGenerator m_ColGenerator = new CLASSI.GridColumnsGenerator();
  
        ISalva m_BindListaISalva = null;
        
        public CodificheControl()
        {
            InitializeComponent();
          
            listViewTabelle.ItemsSource = QueryBase.getAllTablesAndViewsInModel();
                        
            listViewTabelle.DisplayMemberPath = "Name";
            listViewTabelle.SelectedValuePath = "Name";

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                myDataFilter.DysplayerControl = myGrid; 
                myPaginator.DysplayerControl  = myGrid;
                makeDataGrid(ref myGrid, "Documenti");
            }           
                                 
        }//fM

        
        private void btnSalva_Click(object sender, RoutedEventArgs e)
        {
            myGrid.CommitEdit();

           //var salva = myGrid.ItemsSource as ISalva ;
            int tot = m_BindListaISalva.salvaDati(); 

            //var dtv = myGrid.ItemsSource as DataView;
            //var righeAggiunte = dtv.RowStateFilter = DataViewRowState.Added;
            
            //dtv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            //var righeAggiornate = dtv;
            
            // dtv.RowStateFilter = DataViewRowState.Deleted ;
            // var righeCancellate = dtv;

            //m_BindListaISalva.salvaDati(); 
        }//fM

        private void listViewTabelle_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var it = e.Source;
            var tabSelected = listViewTabelle.SelectedValue.ToString();
                
            /*
            DocManagerORM.OPF3.OPF3Database opf =
                new DocManagerORM.OPF3.OPF3Database(DocManagerORM.OPF3.DBEnum.MsSql, "DocManagerDb", true);

            var set = opf.getObjectSet<DocManagerORM.Entità.Categorie>(null).ToList() ;
            */

            makeDataGrid(ref myGrid, tabSelected);
            
        }//fM
              

        private void makeDataGrid(ref DataGrid pDG,string pTableName)
        {
            pDG.ItemsSource = null;
            pDG.Items.Clear();
            pDG.Columns.Clear();
            pDG.CanUserAddRows = true;

            var listaConstraints =
                new DocManagerORM.Utils.SqlServer("DocManagerDb",true).getConstraintsdefinitionsTable(pTableName); 

            // discovering dell'oggetto campi classe e tutti campi 
            var discover = new DS2171Utils.ObjectDiscover();
            var campiList = discover.getCampiClasseOggetto(pTableName, "DocManagerORM.ORM", "DocManagerORM.dll");
            
            var listCategorie = CacheBase.getDati<Categorie>("Categorie");
            var listSottoCategorie = CacheBase.getDati<SottoCategorie>("SottoCategorie");

            var listSottoCatTutte = CacheBase.getDati<SottoCategorie>("SottoCategorieTutte");
                
            var listRuoli = CacheBase.getDati<aspnet_Roles>("aspnet_Roles");
            var listTags = CacheBase.getDati<Tags>("Tags");
            
            // TODO chiamare la giusta !!!

            var campiClasse = campiList.Item1;//campi classe
            var campiTutti = campiList.Item2;//campi tutti
            
            //
            DataGridColumn col = null;
            
            foreach (var campo in campiTutti)
            {
                if (campiClasse.Contains(campo.Key)) continue;

                var vincolo = listaConstraints.Where(x=> x.InColumn.Equals(campo.Key,
                    StringComparison.InvariantCultureIgnoreCase) & x.Type == "FOREIGN KEY").FirstOrDefault();

                col = null;

                if (vincolo != null)
                {
                    if (vincolo.RelatedTable == "Categorie")
                        col = m_ColGenerator.getComboBoxColumn(campo.Key, "Categoria", "ID", "Fk_IDCat", listCategorie);

                    if (vincolo.RelatedTable == "SottoCategorie")
                    {
                        col = m_ColGenerator.getComboBoxColumn(campo.Key, "Categoria", "ID", "Fk_IDSotCat", listSottoCatTutte);                        
                    }

                    if (vincolo.RelatedTable == "Tags")
                        col = m_ColGenerator.getComboBoxColumn(campo.Key, "TagsPre", "ID", "Fk_IDTags", listTags);

                    if (vincolo.RelatedTable == "aspnet_Roles" & campo.Key.Equals("Fk_RuoliModifica"))
                        col = m_ColGenerator.getComboBoxColumn(campo.Key, "RoleName", "RoleID", "Fk_RuoliModifica", listRuoli);

                    if (vincolo.RelatedTable == "aspnet_Roles" & campo.Key.Equals("Fk_RuoliVedi"))
                        col = m_ColGenerator.getComboBoxColumn(campo.Key, "RoleName", "RoleID", "Fk_RuoliVedi", listRuoli);
                    
                }
                
                if(col == null)
                {
                    if (campo.Value.Contains("System.DateTime"))
                        col = m_ColGenerator.getDateTimeColumn(campo.Key, campo.Key);
                    else if (campo.Value.Contains("System.Boolean"))
                        col = m_ColGenerator.getCheckBoxColumn(campo.Key, campo.Key);
                    else
                        col = m_ColGenerator.getTextBoxColumn(campo.Key, campo.Key);
                }

                pDG.Columns.Add(col);
            }

            //Prelevo i dati e li bindo
            var datiBList = m_QueryCodifiche.getTutteTabelleDati(pTableName, true);//    Documenti>(pTableName);
            
            m_BindListaISalva = datiBList as ISalva; 
            var paginatore = datiBList as IPaginator;
            paginatore.UsaPaginatore = true;
            paginatore.DysplayerControl = pDG;
            paginatore.QuantielementiPerpagina = 20;

            //myPaginator.Paginatore = paginatore;

            pDG.AutoGenerateColumns = false;
            pDG.ItemsSource = datiBList;

            myDataFilter.CreaComboFiltri(campiClasse);
                    
        }//fM

        
        private void myGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            //myGrid.Items.Add(new DocManagerORM.ORM.Categorie());  
            var t = e;
        }

        private void myGrid_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
        {

        }

        private void myGrid_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {

        }

        private void myGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            DataGridRow dgRow = e.Row;
            e.Row.Background = Brushes.Red;  
         
            var dg = sender as DataGrid ;
            var lista2 = dg.ItemsSource as ISalva;
        }

        private void myGrid_SourceUpdated(object sender, DataTransferEventArgs e)
        {

        }

        private void listViewTabelle_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

       

        private void myGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           // myDetails.Content = e.OriginalSource;

        }//fM

        protected object execGenericMethod(Type pClasseContainerMetodo, string pMetodo, Type pTableType)
        {           
            MethodInfo mi = pClasseContainerMetodo.GetMethod(pMetodo);
            MethodInfo miConstructed = mi.MakeGenericMethod(pTableType);
            var res = miConstructed.Invoke(m_QueryCodifiche, null);
            
            //myGrid.ItemsSource = res as IEnumerable;

            return res;
        
        }//fM


        private static void DisplayGenericMethodInfo(MethodInfo mi)
        {
            StringBuilder sb = new StringBuilder();
            
            sb.Append("\r\n : "+ mi);

            sb.Append("\tIs this a generic method definition? "+
                mi.IsGenericMethodDefinition);

            sb.Append("\tIs it a generic method? "+ mi.IsGenericMethod);

            sb.Append("\tDoes it have unassigned generic parameters? "+
                mi.ContainsGenericParameters);

            // If this is a generic method, display its type arguments.
            //
            if (mi.IsGenericMethod)
            {
                Type[] typeArguments = mi.GetGenericArguments();

                sb.Append("\tList type arguments ):"+ typeArguments.Length);

                foreach (Type tParam in typeArguments)
                {
                    // IsGenericParameter is true only for generic type
                    // parameters.
                    //
                    if (tParam.IsGenericParameter)
                    {
                        sb.Append("\t\t{0}  parameter position "+ tParam +"\n\t\t   genericaParPosition :"
                            + tParam.GenericParameterPosition+ ", declaring method : "+ tParam.DeclaringMethod);
                    }
                    else
                    {
                        sb.Append("\t\t"+  tParam);
                    }
                }
            }

            MessageBox.Show(sb.ToString());
            sb.Clear();
        }

        private void myGrid_Error(object sender, ValidationErrorEventArgs e)
        {
           var t = e.Action;

        }//fM


   


    }//fC
}
